/**
 * Created by ayu on 2017/6/29.
 */
const OAuth = require ('wechat-oauth');
const wechatConfig = require ('../../resources/WechatAppConfig');
const client = new OAuth (wechatConfig.app.appid, wechatConfig.app.appsecret);
const oauthDao = require ('../daos/OauthDao');

const getUserAccessToken = ( req, res, next ) =>
{
    let [ code, state ] = [ req.query.code, req.query.state ];
    if (code)
    {
        client.getAccessToken (code, ( err, result ) =>
        {
            if (err)
            {
                console.log (`OAuth 获取用户授权出错: ${err}`);
                return;
            }
            let data = result.data;
            oauthDao.insertWechaterAccessToken (
                {
                    openid       : data.openid,
                    access_token : data.access_token,
                    refresh_token: data.refresh_token,
                    expires_in   : data.expires_in,
                    scope        : data.scope,
                    create_at    : data.create_at
                }, function ( done )
                {
                    if (done.isSuccess)
                    {
                        next ();
                    }
                    else
                    {
                        console.log (`[oauth_token] 重定向 影吧过程，储存用户授权 access_toekn 失败`);
                        next ();
                    }
                });
        });
        
    }
    else
    {
        console.log ('[微信OAuth] 没有收到 code');
        next ();
    }
};
module.exports = {
    getUserAccessToken: getUserAccessToken
};